/**
 * 问题: 发布到网上时request.getContextPath();是什么样
 * */
//var WEBROOT = '/qububu';// 代替request.getContextPath()
/***************************************************公共部分****************************************************/
$(document).ready(function(){
	getOnGoingActivity();
	$("#staff-control").click(loadStaffs);
	$("#food-control").click(loadFoods);
	$("#people-control").click(loadPeoples);
	$("#old-action-control").click(loadOldActions);
});

// 用于装任务列表
var STAFF_LIST;
// 用于判断用户的职务是否刚刚被修改过,针对select的change事件循环触发
var PEOPLE_STAFF_HAND_UPDATE = false;

/*function getWebRoot() {
	var url = window.location.href;
	var webroot = "/" +url.split("/")[3];
	return webroot;
};*/

function getOnGoingActivity() {
	//var basePath = getWebRoot();
	$.ajax({
		url: WEBROOT + "/play/dine/ajaxOngoingOrNearestAction",
		type: "get",
		dataType: "json",
		success: function(res) {
			if (res.result == AjaxMsgConstants.SUCCESS) {
				loadOnGoingAction(res.actionInfo);
			} else {
				alert("数据访问失败");
			}
		}
	});
}

function loadOnGoingAction(actionInfo) {
	if (actionInfo && "" != actionInfo) {
		$("#action-title").html("正在进行的活动:"+actionInfo.actionTitle+"");
		$("#actionId").attr("value", actionInfo.actionId);
		$("#control-box").css({"display":"block"});
	} else {
		// 所有的管理都不需要显示
		$("#action-title").html("当前没有正在进行的活动, 你可以<a href=\""+WEBROOT+"/play/dine/admin/publishAction\" target=\"_blank\">发布活动信息</a>");
	}
}

/***************************************************关于任务****************************************************/

function addStaff() {
	var actionId = $("#actionId").val();
	if (actionId && "" != actionId) {
		STAFF_LIST = null;
		$("#addStaffForm").submit();
	} else {
		if (confirm("页面正在加载数据,请稍等重试,如果该提示重复了3遍,尝试刷新该页面再试, 是否刷新?")) {
			reloadPage();
		}
	}
}

function loadStaffs() {
	var actionId = $("#actionId").val();
	if (actionId && "" != actionId) {
		// 显示列表
		$("#staff-list").css({"display": "block"});
		// 显示"收起字符"
		$("#hiddenStaffListBoxLink").css({"display": "block"});
		$("#hiddenStaffListBoxLink").html("收起");
		$.ajax({
			url: WEBROOT + "/play/dine/getStaffs",
			type: "post",
			dataType: "json",
			data: {"actionId": actionId},
			success: function(res) {
				if (res.result == AjaxMsgConstants.SUCCESS) {
					STAFF_LIST = res.staffs;
					createStaffListToHtml(res.staffs);
				} else {
					alert("出错了"+ res.message);
				}
			}
		});
	} else {
		alert("加载未完成,请稍等,或者刷新重试");
	}
}

function createStaffListToHtml(staffs) {
	var htmlStr = '';
	if (staffs.length > 0) {
		for (var i = 0; i < staffs.length; i++) {
			var staff = staffs[i];
			htmlStr += 
				'<div class="staff-list-row" id="staff-message-'+staff.staffId+'">'+
					'<div class="staff-list-row-name">'+staff.staffName+'</div>'+
					'<div class="staff-list-row-about">'+staff.explain+'</div>'+
					'<div class="staff-list-row-delete">'+
						'<a href="javascript: deleteStaff(\''+staff.staffId+'\')">删除任务</a>'+
					'</div>'+
					'<div class="staff-list-row-edit">'+
						'<a href="javascript: editStaff(\''+staff.staffId+'\')">编辑任务</a>'+
					'</div>'+
					'<div style="clear: both;"></div>'+
				'</div>';
			htmlStr += 
				'<div class="staff-list-row" style="display: none;" id="modifystaff-box-'+staff.staffId+'">'+
					'<div class="staff-list-row-name" style="font-size: 12px;"><input type="text" style="height: 30px; margin: 5px; width: 120px;" name="staffName" value="'+staff.staffName+'" title="输入职务名" /></div>'+
					'<div class="staff-list-row-about">'+
						'<textarea style="height: 40px; width: 200px" name="explain" title="输入职务简介">'+staff.explain+'</textarea>'+
						'<input type="hidden" name="staffId" value="'+staff.staffId+'">'+
					'</div>'+
					'<div class="staff-list-row-delete">'+
						'<a href="javascript: doModifyStaff(\''+staff.staffId+'\')">确认修改</a>'+
					'</div>'+
					'<div class="staff-list-row-edit">'+
						'<a href="javascript: hiddenModifyStaffBox(\''+staff.staffId+'\')">取消</a>'+
					'</div>'+
				'</div>';
		}
	} else {
		htmlStr = '<div style="width: 100%; height: 40px; line-height: 40px; text-align: center;">暂时没有任务信息,去<a href="javascript:addStaff()">添加职务</a></div>';
	}
	$("#staff-list-content").html(htmlStr);
}

/**
 * 删除任务
 */
function deleteStaff(staffId) {
	if (staffId && "" != staffId) {
		$("#staff-message-"+staffId+"").css({"display": "none"});
		hiddenModifyStaffBox(staffId);
		$.ajax({
			url: WEBROOT +'/play/dine/admin/deleteStaff',
			type: 'post',
			dataType: 'json',
			data: {"staffId": staffId},
			success: function(res) {
				if (res.result == AjaxMsgConstants.SUCCESS) {
					removeStaffListFromPage(staffId);
					alert("删除职务成功");
					STAFF_LIST = null;
				} else {
					alert("删除职务失败");
					$("#staff-message-"+staffId+"").css({"display": "block"});
				}
			}
		});
	}
}

function removeStaffListFromPage(staffId) {
	$("#staff-message-"+staffId+"").html("");
	$("#modifystaff-box-"+staffId+"").html("");
}

/**
 * 显示修改的框框
 * */
function editStaff(staffId) {
	$("#modifystaff-box-"+staffId+"").css({"display": "block"});
}

function hiddenModifyStaffBox(staffId) {
	$("#modifystaff-box-"+staffId+"").css({"display": "none"});
}

/**
 * 确认修改职务信息
 */
function doModifyStaff(staffId) {//有没有点击修改但是还是会修改的小bug
	if (staffId && "" != staffId) {
//		var staffId = $("#modifystaff-box-"+staffId+" :input[name='staffId']").val();
		var nowStaffNode = $("#staff-message-"+staffId+"");
		var nowStaffName = nowStaffNode.children(".staff-list-row-name").html();
		var nowStaffExplain = nowStaffNode.children(".staff-list-row-about").html();
		var staffName = $("#modifystaff-box-"+staffId+" :input[name='staffName']").val();
		//var explain = $("#modifystaff-box-"+staffId+" :input[name='explain']").val();
		var explain = $("#modifystaff-box-"+staffId+" textarea").val();
		if (staffId && "" != staffId && staffName && "" != staffName && explain && "" != explain
				&& (staffName != nowStaffName || nowStaffExplain != explain)) {
			hiddenModifyStaffBox(staffId);
			$.ajax({
				url: WEBROOT+"/play/dine/admin/modifyStaff",
				type: "post",
				dataType: "json",
				data: {
					"staffId": staffId,
					"staffName": staffName,
					"explain": explain
				},
				success: function(res) {
					if (res.result == AjaxMsgConstants.SUCCESS) {
						// 修改页面显示数据
						changeShowStaffMessage(staffName, explain, staffId);
						alert("修改职务成功");
					} else {
						editStaff(staffId);
						alert("修改职务失败");
					}
				}
			});
		} else {
			alert("请先完善数据");
		}
	}
}

// 修改页面显示的职务信息数据
function changeShowStaffMessage(staffName, explain, staffId) {
	var staffNode = $("#staff-message-"+staffId+"");
	staffNode.find(".staff-list-row-name").html(staffName);
	staffNode.find(".staff-list-row-about").html(explain);
}

function hiddenOrShowStaffListBox() {
	if ($("#staff-list").css("display") == "block") {
		$("#staff-list").css({"display": "none"});
		$("#hiddenStaffListBoxLink").html("显示");
	} else {
		$("#staff-list").css({"display": "block"});
		$("#hiddenStaffListBoxLink").html("收起");
	}
}

/***************************************************关于菜品****************************************************/
function addFood() {
	var actionId = $("#actionId").val();
	if (actionId && "" != actionId) {
		$("#actionId-food").val(actionId);
		var id = $("#actionId-food").val();
		if (id && "" != id) {
			$("#addFoodForm").submit();
		} else {
			if (confirm("页面正在加载数据,请稍等重试,如果该提示重复了3遍,尝试刷新该页面再试, 是否刷新?")) {
				reloadPage();
			}
		}
	} else {
		if (confirm("页面正在加载数据,请稍等重试,如果该提示重复了3遍,尝试刷新该页面再试, 是否刷新?")) {
			reloadPage();
		}
	}
}

function loadFoods() {
	var actionId = $("#actionId").val();
	if (actionId && "" != actionId) {
		// hiddenOrShowFoodListBox();
		$("#food-list-box").css({"display": "block"});
		$("#hiddenOrShowFoodListLink").html("收起");
		$("#hiddenOrShowFoodListLink").css({"display": "block"});
		$.ajax({
			url: WEBROOT +"/play/dine/getFoods",
			type: "post",
			dataType: "json",
			data: {"actionId": actionId},
			success: function(res) {
				if (res.result == AjaxMsgConstants.SUCCESS) {
					createFoodListHtml(res.foods);
				} else {
					alert("出错了" + res.message);
				}
			}
		});
	} else {
		alert("请稍后重试");
	}
}

function createFoodListHtml(foods) {
	var htmlStr = '';
	if (foods && foods.length > 0) {
		for (var i = 0; i < foods.length; i++) {
			var food = foods[i];
			var isStapleFood = '否';
			if (food.stapleFood == "ISSTAPLE") {
				isStapleFood = "<b style='color:red;'>是</b>";
			}
			htmlStr += 
				'<div class="food-list-row" id="food-list-row-'+food.foodId+'" style="height: 120px; line-height: 120px; width: 790px; margin-top: 3px; border-top: 1px dashed #AED4F5;">'+
					'<div style="float: left; width: 160px; height: 120px; text-align: center; margin-left: 5px;">'+
						'<img src="'+food.foodPic+'" alt="菜品图片,正在加载" style="max-height: 120px; max-width: 120px;">'+
					'</div>'+
					'<div style="float: left; width: 160px; height: 120px; margin-left: 15px;">'+food.foodName+'</div>'+
					'<div style="float: left; width: 80px; height: 120px; margin-left: 15px; text-align: center;">'+isStapleFood+'</div>'+
					'<div style="float: left; width: 100px; height: 120px; margin-left: 15px;">'+
						'<a href="javascript:deleteFood(\''+food.foodId+'\')">删除</a>'+
					'</div>'+
					'<div style="clear: both;"></div>'+
				'</div>';
		}
		
	} else {
		htmlStr = '<div style="height: 40px; line-height: 40px; width: 790px; text-align: center;">当前还没有食谱, 去<a href="javascript:addFood()">添加</a></div>';
	}
	$("#food-list-content").html(htmlStr);
}

function deleteFood(foodId) {
	$("#food-list-row-"+foodId).css({"display": "none"});
	if (foodId && "" != foodId) {
		$.ajax({
			url: WEBROOT +"/play/dine/admin/ajaxDeleteFood",
			type: "post",
			dataType: "json",
			data: {"foodId": foodId},
			success: function(res) {
				if (res.result == AjaxMsgConstants.SUCCESS) {
					$("#food-list-row-"+foodId).html("");
					alert("删除菜品成功");
				} else {
					$("#food-list-row-"+foodId).css({"display": "block"});
					alert("删除菜品失败");
				}
			}
		});
	}
}

/**
 * 获取到食谱列表后改变页面样式以及点击书谱列表右上方的显示or收起时的样式变化
 * */
function hiddenOrShowFoodListBox() {
	if ($("#food-list-box").css("display") == "block") {
		$("#food-list-box").css({"display": "none"});
		$("#hiddenOrShowFoodListLink").html("显示");
	} else {
		$("#food-list-box").css({"display": "block"});
		$("#hiddenOrShowFoodListLink").html("收起");
	}
}

/**********************************************参与活动的成员使用**************************************************/
function loadPeoples() {
	var actionId = $("#actionId").val();
	if (actionId && "" != actionId) {
		$("#people-list").css({"display": "block"});
		$("#changePeopleListBoxDisplayLink").html("收起");
		$("#changePeopleListBoxDisplayLink").css({"display": "block"});
		$.ajax({
			url: WEBROOT +"/play/dine/getPeoples",
			type: "post",
			dataType: "json",
			data: {"actionId": actionId},
			success: function(res) {
				if (res.result == AjaxMsgConstants.SUCCESS) {
					if (!STAFF_LIST || "" == STAFF_LIST) {
						// 加载任务列表
						$.ajax({
							url: WEBROOT + "/play/dine/getStaffs",
							type: "post",
							dataType: "json",
							data: {"actionId": actionId},
							success: function(staffRes) {
								if (staffRes.result == AjaxMsgConstants.SUCCESS) {
									STAFF_LIST = staffRes.staffs;
									createPeoplesHtmlStr(STAFF_LIST, res.peoples);
								} else {
									alert("出错了"+ staffRes.message);
								}
							}
						});
					} else {
						createPeoplesHtmlStr(STAFF_LIST, res.peoples);
					}
				} else {
					alert("出错了" + res.message);
				}
			}
		});
	} else {
		alert("请稍后重试");
	}
}

function createPeoplesHtmlStr(staffs, peoples) {
	if (peoples.length > 0) {
		var notHaveStaffId = "hWlaWDNgTqiIbWB2tkBZhQ";
		var staffSelectStr = '<select class="people-staff" style="width: 80px; height: 28px; margin-top: 3px;"><option value="'+notHaveStaffId+'">无职务';
		for (var i = 0; i < staffs.length; i++) {
			var staff = staffs[i];
			staffSelectStr += '<option value="'+staff.staffId+'">' + staff.staffName;
		}
		staffSelectStr += '</select>';
		$("#people-list").html("");
		for (var j = 0; j < peoples.length; j++) {
			var people = peoples[j];
			var htmlStr = 
				'<div class="people-list-info" id="people-list-info-'+people.peopleId+'" style="float: left; width: 100px; height: 80px; margin: 5px; border: 1px dashed #AED4F5">'+
					'<div class="people-list-info-name" style="width: 100px; height: 40px; line-height: 40px; text-align: center;" title="成员用户名">'+people.peopleName+'</div>'+
					'<div class="people-list-info-staff" style="width: 80px; margin: 0 9px; height: 30px; line-height: 30px; border-top: 1px dashed #AED4F5;" title="选中的为该成员当前职务,重新选择职务便可以改变其职务">'+
						'<input type="hidden" name="peopleId" value="'+people.peopleId+'" />'+ staffSelectStr +
					'</div>'+
				'</div>';
			if (j > 0 && j % 7 == 0) {
				htmlStr += '<div style="clear: both;"></div>';
			}
			$("#people-list").append(htmlStr);
			$("#people-list-info-"+people.peopleId+" select option[value=\""+people.staffId+"\"]").attr({"selected": "selected"});
			// 加载select的change事件
			//$(".people-staff").change(peopleStaffChange);
			$(".people-staff").click(peopleStaffChange);
		}
	} else {
		var htmlStr = '<div style="width: 790px; height: 40px; line-height: 40px; text-align: center;">目前没有参加该活动的人员</div>';
		$("#people-list").html(htmlStr);
	}
	// 创建各种列表
	//alert("staffs-length-"+staffs.length);
	//alert("peoples-length-"+peoples.length);
}

function changePeopleListBoxDisplay() {
	if ($("#people-list").css("display") == "none") {
		$("#people-list").css({"display": "block"});
		$("#changePeopleListBoxDisplayLink").html("收起");
	} else {
		$("#people-list").css({"display": "none"});
		$("#changePeopleListBoxDisplayLink").html("显示");
	}
	
}

/**
 * 每个人职务变化时调用的事件
 * */
function peopleStaffChange() {
	var nowStaffValue = $(this).children('option:selected').val();
	var nowStaffName = $(this).children('option:selected').html();
	PEOPLE_STAFF_HAND_UPDATE = false;
	$(this).change(function() {
		if (!PEOPLE_STAFF_HAND_UPDATE) {
			var newStaffValue = $(this).children('option:selected').val();
			if (nowStaffValue != newStaffValue) {
				var newStaffName = $(this).children('option:selected').html();
				if (confirm("你确定要将该用户的职务从“"+nowStaffName+"”变为“"+newStaffName+"”")) {
					PEOPLE_STAFF_HAND_UPDATE = true;
					var peopleId = $(this).parent(".people-list-info-staff").children("input[name=\"peopleId\"]").val();
					doUpdatePeopleStaff(peopleId, newStaffValue, nowStaffValue, this);
				} else {
					$(this).children("option[value=\""+nowStaffValue+"\"]").attr({"selected": "selected"});
				}
			}
		}
	});
}

/**
 * 提交到后台改变职务并改变其样式
 * @param peopleId 参加人员的ID
 * @param staffId 新的职务ID
 * @param oldStaffValue 修改前的职务ID
 * @param selectObj 当前操作的select对象
 * */
function doUpdatePeopleStaff(peopleId, staffId, oldStaffValue, selectObj) {
	$(selectObj).attr({"disabled": true});
	$.ajax({
		url: WEBROOT + "/play/dine/admin/changePeopleStaff",
		type: "post",
		dataType: "json",
		data: {"peopleId": peopleId, "staffId": staffId},
		success: function(res) {
			if (res.result == AjaxMsgConstants.SUCCESS) {
				alert("修改成功");
			} else {
				alert("修改失败,请稍后重试,错误代码："+res.message);
				// 如果失败
				$(selectObj).children("option[value=\""+oldStaffValue+"\"]").attr({"selected": "selected"});
			}
			$(selectObj).attr({"disabled": false});
		}
	});
}

/**********************************************管理过期活动的各种相关**************************************************/
function loadOldActions() {
	$("#old-action-list-top").css({"display": "block"});
	$("#old-action-list").css({"display": "block"});
	$("#changeOldActionListBoxDisplayLink").html("收起");
	$("#changeOldActionListBoxDisplayLink").css({"display": "block"});
	$.ajax({
		url: WEBROOT +"/play/dine/getOutdatedActions",
		type: "post",
		dataType: "json",
		success: function(res) {
			if (res.result == AjaxMsgConstants.SUCCESS) {
				createOldActionListHtml(res.actions);
			} else {
				alert("出错了" + res.message);
			}
		}
	});
}
function createOldActionListHtml(actions) {
	$("#old-action-list").html("");
	for (var i = 0; i < actions.length; i++) {
		var action = actions[i];
		var beginTime = new Date();
		beginTime.setTime(action.beginTime * 1000);
		var endTime = new Date();
		endTime.setTime(action.endTime * 1000);
		var htmlStr = '<div style="width: 790px; height: 40px; line-height: 40px;">'+
						  '<div style="float: left; width: 160px; height: 40px; margin-left: 5px;">'+action.actionTitle+'</div>'+
						  '<div style="float: left; width: 160px; height: 40px; text-align: center; margin-left: 5px;">'+beginTime.format("yyyy年MM月dd日")+'</div>'+
						  '<div style="float: left; width: 160px; height: 40px; text-align: center; margin-left: 5px;">'+endTime.format("yyyy年MM月dd日")+'</div>'+
						  '<div style="float: left; width: 120px; height: 40px; margin-left: 5px;">'+action.authorName+'</div>'+
						  '<div class="action-controller" style="float: left; width: 160px; height: 40px; margin-left: 5px;">'+
						  	'<input type="hidden" name="actionId" value="'+action.actionId+'" />';
		if (i == 0) {
			htmlStr += '<a href="javascript:" class="action-summarize">总结</a>';
		} else {
			htmlStr += '<a href="javascript:" class="action-delete">删除</a>';
		}
		htmlStr += '</div>'+
		  		'<div style="clear: both;"></div>'+
		  	'</div>';
		$("#old-action-list").append(htmlStr);
	}
	$(".action-summarize").live('click', gotoSummarize);
	$(".action-delete").live('click', doDeleteAction);
}

function gotoSummarize() {
	var actionId = $(this).parent(".action-controller").find("input[name='actionId']").val();
	var htmlStr = '<form id="gotoSummarizeForm" style="display: none;" action="'+WEBROOT+'/play/dine/admin/infoAddSummarize" method="post" target="_blank"><input type="hidden" name="actionId" value="'+actionId+'"></form>';
	$("#gotoSummarize").html(htmlStr);
	$("#gotoSummarizeForm").submit();
	$("#gotoSummarize").html("");
	$(this).attr({"class": "action-delete"});
	$(this).html("删除");
}

function doDeleteAction() {
	var actionId = $(this).parent(".action-controller").find("input[name='actionId']").val();
	alert("暂时没有实现该功能");
}

function changeOldActionListBoxDisplay() {
	if ($("#old-action-list").css("display") == "none") {
		$("#old-action-list").css({"display": "block"});
		$("#old-action-list-top").css({"display": "block"});
		$("#changeOldActionListBoxDisplayLink").html("收起");
	} else {
		$("#old-action-list").css({"display": "none"});
		$("#old-action-list-top").css({"display": "none"});
		$("#changeOldActionListBoxDisplayLink").html("显示");
	}
}

/**********************************************共用**************************************************/

/**
 * 刷新当前页面 
 */
function reloadPage() {
	window.location.reload();
}
